//
//  HEHealthNoticeViewController.m
//  HealthFamily
//
//  Created by 吴欧 on 2020/12/31.
//  Copyright © 2020 honglutec. All rights reserved.
//

#import "HEHealthNoticeViewController.h"
#import "HEHealthAlarmModel.h"
#import "HEHealthAlarmCell.h"
#import "HEAddNoticeViewController.h"

@interface HEHealthNoticeViewController ()<UITableViewDelegate, UITableViewDataSource, HEHealthAlarmCellDelegate>

@property (nonatomic, strong) NSMutableArray <HEHealthAlarmModel *>* dataSourceArr;
@property (nonatomic, strong) GDTableView *tableView;
@property (nonatomic, strong) UIButton *bottomView;

@end

@implementation HEHealthNoticeViewController

- (NSMutableArray <HEHealthAlarmModel *>*)dataSourceArr {
    if (!_dataSourceArr) {
        _dataSourceArr = [NSMutableArray array];
    }
    return _dataSourceArr;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    self.title = @"健康提醒";
    
    [self setCustomTableView:self.tableView];
    [self showEmpty];
    [self.view addSubview:self.tableView];
    
    [self loadData];
    
    [self initTabBarView];
}

- (GDTableView *)tableView {
    if (!_tableView) {
        _tableView = [[GDTableView alloc] initWithFrame:CGRectMake(0, ZXNavBarHeight , KScreenWidth, KScreenHeight - ZXNavBarHeight - 49 - ZXSafeAreaBottom) style:UITableViewStyleGrouped];
        _tableView.separatorColor = CSplitLineColor;
        _tableView.scrollsToTop = YES;
        _tableView.tableHeaderView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];
        _tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 0.01)];

        _tableView.showsVerticalScrollIndicator = NO;
        _tableView.backgroundColor = CViewBgColor;
        _tableView.delegate = self;
        _tableView.dataSource = self;

        __weak __typeof(&*self)weakSelf = self;
        self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{

            weakSelf.isFromHeadRefresh = YES; 
            [weakSelf loadData];
        }];
  
        [_tableView registerClass:[HEHealthAlarmCell class] forCellReuseIdentifier: KHEHealthAlarmCell];
    }
    return _tableView;
}

- (void)initTabBarView {
    UIButton *bottomView = [UIButton buttonWithType:UIButtonTypeCustom];
    _bottomView = bottomView;
    [self.view addSubview:bottomView];
    bottomView.backgroundColor = CNavBgColor;
    _bottomView.titleLabel.font = DYBlodFont(18);
    [bottomView setTitleColor:KWhiteColor forState:UIControlStateNormal];
    [bottomView addTarget:self action:@selector(add) forControlEvents:UIControlEventTouchUpInside];
    
    [bottomView setTitle:@"新增用药提醒" forState:UIControlStateNormal];
    
    [bottomView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.right.bottom.equalTo(self.view);
        make.height.mas_offset(49);
        make.bottom.offset(-ZXSafeAreaBottom);
    }];
}

- (void)add {
    HEAddNoticeViewController *vc = [HEAddNoticeViewController new];
    vc.model = [HEHealthAlarmModel new];
    vc.backBlock = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -

- (void)loadData {
    
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KServerAlarms parameters:@{} success:^(id  _Nonnull responseObject) {
        NSLog(@"response：  %@", [responseObject mj_JSONString]);

        if (self.isFromHeadRefresh) {
            [self.dataSourceArr removeAllObjects];
        }

        HEArrayResponse *response = [HEArrayResponse mj_objectWithKeyValues:responseObject];

        [self.dataSourceArr addObjectsFromArray:[HEHealthAlarmModel mj_objectArrayWithKeyValuesArray:response.data]];
        [self.tableView reloadData];

        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];

        if (self.dataSourceArr.count == 0) {
            [self showEmpty];
        }else {
            if (response.data.count == 0) {
                [Dialog toastBottom:@"没有更多数据了~"];
            }
        }

    } failure:^(NSError * _Nonnull error) {
        [self.tableView.mj_header endRefreshing];
        [self.tableView.mj_footer endRefreshing];
    }];
}

#pragma mark - UITableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.dataSourceArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    HEHealthAlarmCell *cell = [_tableView dequeueReusableCellWithIdentifier: KHEHealthAlarmCell];
    cell.model = self.dataSourceArr[indexPath.row];
    cell.delegate = self;
    return cell;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
    return [tableView fd_heightForCellWithIdentifier: KHEHealthAlarmCell cacheByIndexPath:indexPath configuration:^(HEHealthAlarmCell *cell) {
        cell.model = self.dataSourceArr[indexPath.row];
    }];
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    HEHealthAlarmModel *model = self.dataSourceArr[indexPath.row];
    HEAddNoticeViewController *vc = [HEAddNoticeViewController new];
    vc.model = [model mutableCopy];
    vc.backBlock = ^{
        [self.tableView.mj_header beginRefreshing];
    };
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark -
- (NSArray<UITableViewRowAction *> *)tableView:(UITableView *)tableView editActionsForRowAtIndexPath:(NSIndexPath *)indexPath {
//    UITableViewRowAction *editAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleNormal title:@"编辑" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
//        // 收回侧滑
//        [tableView setEditing:NO animated:YES];
//
//        HEEditAddressViewController *vc = [HEEditAddressViewController new];
//        vc.model = self.dataSourceArr[indexPath.row];
//        vc.type = HEEditAddressTypeUpdate;
//        [vc vcBackBlock:^{
//            [self.tableView.mj_header beginRefreshing];
//        }];
//        [self.navigationController pushViewController:vc animated:YES];
//    }];
//    editAction.backgroundColor = CNavBgColor;

    UITableViewRowAction *deleteAction = [UITableViewRowAction rowActionWithStyle:UITableViewRowActionStyleDestructive title:@"删除" handler:^(UITableViewRowAction * _Nonnull action, NSIndexPath * _Nonnull indexPath) {
        [self deleteRow:self.dataSourceArr[indexPath.row].inst_id indexPath:indexPath];
    }];

    return @[deleteAction];
}

- (void)deleteRow:(NSString *)inst_id indexPath:(NSIndexPath *)indexPath {
    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KServerDeleteAlarms parameters:@{@"inst_id": inst_id} success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.success) {
            [self.tableView.mj_header beginRefreshing];

//            // 删除cell: 必须要先删除数据源，才能删除cell
//            [self.dataSourceArr removeObjectAtIndex:indexPath.row];
//            [self.tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

#pragma mark - HEHealthAlarmCellDelegate
- (void)cellOpenNotice:(HEHealthAlarmModel *)model status:(NSInteger)status {

    HEHealthAlarmModel *req = [model mutableCopy];
    req.alarm_state = status;

    [WOAFNetWorkingHandle POSTWithBaseUrl:KServerUrl suffixUrl:KServerUpdateAlarms parameters:req success:^(id  _Nonnull responseObject) {
        HEResponse *response = [HEResponse mj_objectWithKeyValues:responseObject];

        if (response.success) {
            [Dialog toastBottom:@"操作成功"];
            model.alarm_state = status;
            [self.tableView reloadData];
        }
    } failure:^(NSError * _Nonnull error) {

    }];
}

@end
